import React, { Component } from 'react';
import withdrawStyle from './WithdrawWrap.scss';
import { Input, Radio, message } from 'antd';
import MModal from '@/component/common/MModal';
import OperModal from '@/component/common/OperModal';
import ApiHelper from '@/store/ApiHelper';
import { balance, withdraw_apply, withdraw_list } from '@/constants/ApiTypes';
const RadioGroup = Radio.Group;

class WithdrawWrap extends Component {
    state = {
        withdrawModalVisible: false,
        withdrawModalInputValue: '',
        balance: false,
        withdrawAccountList: [],
        withdrawAccount: false
    };
    async componentDidMount() {
        this._isMounted = true;
        //获取联盟店余额
        const result = await ApiHelper.requestPost(balance, {}, true);
        if (!this._isMounted) return;
        this.setState({
            balance: result.info.balance
        });
    }
    componentWillUnmount() {
        this._isMounted = false;
    }
    withdrawApply = () => {
        const { balance, withdrawAccount: account_id } = this.state;
        const data = {
            money: balance * 100,
            account_id
        };
        return ApiHelper.requestPost(withdraw_apply, data, true);
    };
    withdrawModalConfirm = async () => {
        let { withdrawModalInputValue: value, withdrawAccount: account_id } = this.state;
        if (value === '') {
            this.withdrawInput.focus();
            return message.error('请填写提现金额！', 1.5);
        }
        if (value <= 0) {
            this.withdrawInput.refs.input.select();
            return message.error('提现金额必须大于0！', 1.5);
        }
        if (account_id === false) return message.error('请选择提现账户');

        const result = await this.withdrawApply();
        if (result.status) {
            MModal.success({ title: '操作成功', content: result.info });
            this.closeWithdrawModal();
        } else {
            MModal.success({ title: '操作失败', content: result.info });
        }
    };
    withdrawModalCancel = () => this.closeWithdrawModal();
    showWithdrawModal = async () => {
        if (this.state.withdrawModalVisible) return;
        const result = await ApiHelper.requestPost(withdraw_list);
        if (!result.status) return  MModal.success({ title: '错误提示', content: result.info, duration: 1.5 });
        this.setState({
            withdrawModalVisible: true,
            withdrawAccountList: result.info
        });
        setTimeout(() => {
            this.withdrawInput.focus();
        });
    };
    closeWithdrawModal = () => {
        this.setState({
            withdrawModalVisible: false,
            withdrawModalInputValue: ''
        });
    };
    withdrawModalInputValueChange = e => {
        let value = e.target.value;
        //清除"数字"和"."以外的字符
        value = value.replace(/[^\d.]/g, "");
        //验证第一个字符是数字而不是
        value = value.replace(/^\./g, "");
        //只保留第一个. 清除多余的
        value = value.replace(/\.{2,}/g, ".");
        value = value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
        //只能输入两个小数
        value = value.replace(/^(-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
        if (value !== '') {
            let value2 = value.split('.');
            if (value2[0].length > 9) {
                value = value2[0].substr(0, 9) + (value2[1] ? '.' + value2[1] : '');
            }
        }
        this.setState({ withdrawModalInputValue: value });
    };
    selectWithdrawAccount = e => {
        this.setState({ withdrawAccount: e.target.value });
    };
    render() {
        const { withdrawModalInputValue, balance, withdrawAccountList, withdrawAccount } = this.state;
        let AccountComponent;
        if (Array.isArray(withdrawAccountList)) {
            AccountComponent = <RadioGroup onChange={this.selectWithdrawAccount} value={withdrawAccount}>
                {withdrawAccountList.map((val) => {
                    return <Radio key={val.account_id} value={val.account_id}>{val.account_type_desc}[{val.account}]</Radio>
                })}
            </RadioGroup>
        } else {
            AccountComponent = <span style={{ color: 'red' }}>{withdrawAccountList}</span>;
        }
        return (
            <div className={withdrawStyle['withdraw-wrap']}>
                <div className={withdrawStyle.ac}><span>账户资金安全保障中</span><img className={withdrawStyle['icon-shield']} src="/static/alliance2/image/welcome/baozhang.png" /></div>
                <div className={withdrawStyle.bl}><span>余额</span><span className={withdrawStyle.money}>{balance === false ? '读取中...' : balance / 100 + '元'}</span></div>
                <a className={withdrawStyle['withdraw-btn']} href="javascript:void(0);" onClick={this.showWithdrawModal}>提现</a>
                <OperModal
                    title="提现"
                    visible={this.state.withdrawModalVisible}
                    onOk={this.withdrawModalConfirm}
                    onClose={this.withdrawModalCancel}
                    width={350}
                    height={180}
                >
                    <h3 className={withdrawStyle['label-text']}>选择提现账户：</h3>
                    {AccountComponent}
                    <h3 className={withdrawStyle['label-text']}>输入提现金额：</h3>
                    <Input
                        ref={input => this.withdrawInput = input}
                        value={withdrawModalInputValue}
                        style={{ width: '50%' }}
                        onChange={this.withdrawModalInputValueChange} /> 元
                </OperModal>
            </div>
        );
    }
}

export default WithdrawWrap;